<template>
  <!-- <div v-if="loading">加载中...</div> -->
  <BuilderItem v-if="fields.length" :model="model" :fields="fields" />
</template>

<script>
import BuilderItem from './BuilderItem.vue'
import { check } from './index.js'
export default {
  components: { BuilderItem },
  props: {
    default: {
      type: Object,
      default: () => ({})
    },
    api: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      model: this.default,
      fields: [],
      loading: false
    }
  },
  mounted() {
    if (this.api) this.getFields()
  },
  watch: {
    default(val) {
      this.model = val
    },
    api(val) {
      this.getFields()
    },
    model: {
      handler(val) {
        this.$emit('result', {
          data: val,
          valid: !check(val, this.fields)
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getFields () {
      this.loading = true
      fetch(this.api).then((response) => {
        response.json().then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.fields = res.data.rows
            this.$emit('result', {
              data: this.model,
              valid: !check(this.model, this.fields)
            })
          } else {
            console.log(res.message)
          }
        })
      })
    }
  }
}
</script>